import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/app/router/app_router.dart';
import 'package:vista/features/community/viewmodels/community_viewmodel.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/models/group_snapshot.dart';
import 'package:vista/shared/models/moment_shot.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/utils/widget_extension.dart';
import 'package:vista/shared/widgets/auth_gate_modal.dart';
import 'package:vista/shared/widgets/complain_bottom_sheet.dart';
import 'package:vista/shared/widgets/join_circle_dialog.dart';
import 'package:vista/main.dart' as app;

/// 社区视图
/// 社区功能页面
class CommunityView extends StatefulWidget {
  const CommunityView({super.key});

  @override
  State<CommunityView> createState() => _CommunityViewState();
}

class _CommunityViewState extends State<CommunityView>
    with WidgetsBindingObserver, RouteAware {
  final PageController _pageController = PageController();
  int _currentPage = 0;
  CommunityViewModel? _viewModel;

  // 瀑布流默认高度列表（单位：像素）
  static const List<double> _waterfallHeights = [
    180.0,
    220.0,
    200.0,
    240.0,
    190.0,
    210.0,
    230.0,
    195.0,
    225.0,
    205.0,
  ];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route is PageRoute) {
      app.routeObserver.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    app.routeObserver.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    _pageController.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用从后台恢复时，刷新登录状态
    if (state == AppLifecycleState.resumed && _viewModel != null) {
      _viewModel!.refresh();
    }
  }

  @override
  void didPopNext() {
    // 当从其他页面返回到此页面时刷新
    if (_viewModel != null) {
      _viewModel!.refresh();
    }
  }

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<CommunityViewModel>.reactive(
      viewModelBuilder:
          () =>
              CommunityViewModel(getIt.get(), getIt.get(), getIt.get())
                ..initialize(),
      onViewModelReady: (viewModel) {
        _viewModel = viewModel;
      },
      builder: (context, model, child) {
        if (model.isBusy) {
          return Scaffold(
            body: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/my-background.png'),
                  fit: BoxFit.fill,
                ),
              ),
              child: const Center(child: CircularProgressIndicator()),
            ),
          );
        }

        return Scaffold(
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my-background.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: SafeArea(
              bottom: false,
              child: [
                // 标题栏
                _buildHeader(context, model),
                // 圈子列表
                _buildCirclesList(context, model),
                SizedBox(height: 20.h),
                // 页面指示器
                _buildPageIndicator(context),
                SizedBox(height: 14.h),
                // 动态内容（PageView）
                Expanded(
                  child: PageView(
                    controller: _pageController,
                    onPageChanged: (index) {
                      setState(() {
                        _currentPage = index;
                      });
                    },
                    children: [
                      // 日常生活动态
                      _buildDailyLifePage(context, model),
                      // 摄影动态
                      _buildPhotographyPage(context, model),
                    ],
                  ),
                ),
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
            ),
          ),
        );
      },
    );
  }

  /// 构建标题栏
  Widget _buildHeader(BuildContext context, CommunityViewModel model) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 16.h),
      child: Row(
        children: [
          Text(
            'Vista',
            style: TextStyle(
              fontSize: 32.sp,
              fontWeight: FontWeight.w400,
              fontFamily:
                  GoogleFonts.racingSansOne(
                    fontWeight: FontWeight.w400,
                  ).fontFamily,
              color: Colors.black87,
            ),
          ),
          const Spacer(),
          // 发布按钮
          GestureDetector(
            onTap: () async {
              // 检查是否登录
              final currentUser = await getIt<AuthFocus>().getCurrentUser();
              if (currentUser == null) {
                final result = await showDialog<bool>(
                  context: context,
                  builder: (context) => const AuthGateModal(),
                );
                if (result == true && context.mounted) {
                  await Navigator.of(context).pushNamed(Routes.login);
                }
                return;
              }
              // 已登录，跳转到发布页面
              if (context.mounted) {
                final result = await Navigator.of(
                  context,
                ).pushNamed(Routes.publishPost);
                // 返回时刷新数据
                if (result == true && context.mounted) {
                  await model.refresh();
                }
              }
            },
            child: Image.asset(
              'assets/images/upload.png',
              width: 22.w,
              height: 22.h,
              fit: BoxFit.contain,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建圈子列表
  Widget _buildCirclesList(BuildContext context, CommunityViewModel model) {
    if (model.circles.isEmpty) {
      return const SizedBox.shrink();
    }

    return SizedBox(
      height: 86.h,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        padding: EdgeInsets.symmetric(horizontal: 14.w),
        itemCount: model.circles.length,
        itemBuilder: (context, index) {
          return _buildCircleItem(context, model, model.circles[index]);
        },
      ),
    );
  }

  /// 构建单个圈子项
  Widget _buildCircleItem(
    BuildContext context,
    CommunityViewModel model,
    GroupSnapshot group,
  ) {
    final members = model.getCircleMembers(group.id);
    final memberUsers =
        members
            .take(5)
            .map((userId) => model.getUserById(userId))
            .where((user) => user != null)
            .cast<UserFrame>()
            .toList();

    return SizedBox(
      width: 122.w,
      height: 86.h,
      child: GestureDetector(
        onTap: () async {
          // 检查用户是否登录
          if (model.currentUser == null) {
            final result = await showDialog<bool>(
              context: context,
              builder: (context) => const AuthGateModal(),
            );
            if (result == true && context.mounted) {
              await Navigator.of(context).pushNamed('/login');
              if (context.mounted) {
                await model.refreshCurrentUser();
              }
            }
            return;
          }

          // 检查用户是否已加入圈子
          final isMember = await model.isMember(group.id);
          if (isMember) {
            // 已加入，跳转到圈子聊天页面
            if (context.mounted) {
              await Navigator.of(
                context,
              ).pushNamed(Routes.groupChat, arguments: {'groupId': group.id});
            }
          } else {
            // 未加入，显示加入确认弹窗
            final confirm = await JoinCircleDialog.show(context, group.title);
            if (confirm == true && context.mounted) {
              // 加入圈子
              await model.joinCircle(group.id);
              if (context.mounted) {
                // 提示加入成功
                FlashNotifier.flashSuccess('Joined successfully!');
                // 跳转到圈子聊天页面
                await Navigator.of(
                  context,
                ).pushNamed(Routes.groupChat, arguments: {'groupId': group.id});
              }
            }
          }
        },
        child: Container(
          margin: EdgeInsets.only(right: 12.w),
          decoration: BoxDecoration(
            image: const DecorationImage(
              image: AssetImage('assets/images/circle-box.png'),
              fit: BoxFit.fill,
            ),
            borderRadius: BorderRadius.circular(6.r),
          ),
          child: Padding(
            padding: EdgeInsets.only(
              left: 8.w,
              right: 0.w,
              top: 0.w,
              bottom: 0.h,
            ),
            child: [
              // 第一排：圈子名称和图片
              Row(
                children: [
                  // 圈子名称（最多两排）
                  Expanded(
                    child: Text(
                      group.title,
                      style: TextStyle(
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w800,
                        fontFamily:
                            GoogleFonts.alegreyaSans(
                              fontWeight: FontWeight.w800,
                            ).fontFamily,
                        color: Colors.black87,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  SizedBox(width: 4.w),
                  // 圈子图片
                  ClipRRect(
                    child: Image.asset(
                      group.image,
                      width: 40.w,
                      height: 40.w,
                      fit: BoxFit.cover,
                    ),
                  ),
                ],
              ),
              const Spacer(),
              // 第二排：用户头像叠层
              if (memberUsers.isNotEmpty)
                SizedBox(
                  height: 18.h,
                  child: Stack(
                    clipBehavior: Clip.none,
                    children: [
                      // 最多显示4个头像
                      for (int i = 0; i < memberUsers.length && i < 4; i++)
                        Positioned(
                          left: i * 12.0.w,
                          child: CircleAvatar(
                            radius: 9.r,
                            backgroundColor: Colors.white,
                            backgroundImage:
                                memberUsers[i].avatar != null
                                    ? AssetImage(memberUsers[i].avatar!)
                                    : null,
                            child:
                                memberUsers[i].avatar == null
                                    ? Icon(
                                      Icons.person,
                                      size: 10.w,
                                      color: Colors.grey,
                                    )
                                    : null,
                          ),
                        ),
                      // 如果成员超过4个，显示一个带图标的圆
                      if (memberUsers.length > 4)
                        Positioned(
                          left: 4 * 12.0.w,
                          child: Container(
                            width: 18.w,
                            height: 18.w,
                            decoration: BoxDecoration(
                              color: ColorConstants.primaryColor,
                              shape: BoxShape.circle,
                            ),
                            child: Icon(
                              Icons.more_horiz,
                              size: 10.w,
                              color: Colors.white,
                            ),
                          ),
                        ),
                    ],
                  ),
                ),
              const Spacer(),
            ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
          ),
        ),
      ),
    );
  }

  /// 构建页面指示器
  Widget _buildPageIndicator(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 14.w),
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              _pageController.animateToPage(
                0,
                duration: const Duration(milliseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
              decoration: BoxDecoration(
                color:
                    _currentPage == 0
                        ? ColorConstants.accentColor
                        : Colors.transparent,
                borderRadius: BorderRadius.circular(4.r),
              ),
              child: Text(
                'Daily routine',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                  fontFamily:
                      GoogleFonts.alegreyaSans(
                        fontWeight: FontWeight.w600,
                      ).fontFamily,
                  color: _currentPage == 0 ? Colors.white : Colors.black54,
                ),
              ),
            ),
          ),
          SizedBox(width: 16.w),
          GestureDetector(
            onTap: () {
              _pageController.animateToPage(
                1,
                duration: const Duration(milliseconds: 300),
                curve: Curves.easeInOut,
              );
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
              decoration: BoxDecoration(
                color:
                    _currentPage == 1
                        ? ColorConstants.accentColor
                        : Colors.transparent,
                borderRadius: BorderRadius.circular(4.r),
              ),
              child: Text(
                'Photography',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                  fontFamily:
                      GoogleFonts.alegreyaSans(
                        fontWeight: FontWeight.w600,
                      ).fontFamily,
                  color: _currentPage == 1 ? Colors.white : Colors.black54,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建日常生活动态页面
  Widget _buildDailyLifePage(BuildContext context, CommunityViewModel model) {
    if (model.dailyLifePosts.isEmpty) {
      return Center(
        child: Text(
          'No daily life posts yet',
          style: TextStyle(fontSize: 14.sp, color: Colors.grey),
        ),
      );
    }

    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 14.w),
      child: [
        for (int i = 0; i < model.dailyLifePosts.length; i++) ...[
          _buildDailyLifeItem(context, model, model.dailyLifePosts[i]),
          if (i < model.dailyLifePosts.length - 1) SizedBox(height: 14.h),
        ],
        SizedBox(height: 100.h), // 底部留白
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
    );
  }

  /// 构建单个日常生活动态项
  Widget _buildDailyLifeItem(
    BuildContext context,
    CommunityViewModel model,
    MomentShot post,
  ) {
    final user = model.getUserById(post.authorId);

    return GestureDetector(
      onTap: () async {
        await Navigator.of(
          context,
        ).pushNamed(Routes.momentDetail, arguments: {'postId': post.id});
        await model.refresh();
      },
      child: AspectRatio(
        aspectRatio: 347 / 300,
        child: Stack(
          children: [
            // 背景图片
            Container(
              decoration: BoxDecoration(
                image: const DecorationImage(
                  image: AssetImage('assets/images/daily-routine.png'),
                  fit: BoxFit.fill,
                ),
                borderRadius: BorderRadius.circular(6.r),
                boxShadow: [
                  BoxShadow(
                    color: ColorConstants.blackColor,
                    blurRadius: 0,
                    offset: Offset(2, 2),
                    spreadRadius: 0,
                  ),
                ],
              ),
            ),
            // 内容
            Padding(
              padding: EdgeInsets.only(
                left: 14.w,
                right: 14.w,
                top: 32.w,
                bottom: 27.h,
              ),
              child: [
                // 用户信息行
                Row(
                  children: [
                    // 用户头像
                    GestureDetector(
                      onTap: () async {
                        if (user == null) return;
                        // 检查是否是当前用户
                        final currentUser =
                            await getIt<AuthFocus>().getCurrentUser();
                        if (currentUser != null && currentUser.id == user.id) {
                          return; // 是自己的头像，不跳转
                        }
                        // 跳转到他人主页
                        if (context.mounted) {
                          await Navigator.of(context).pushNamed(
                            Routes.otherProfile,
                            arguments: {'userId': user.id},
                          );
                        }
                      },
                      child: CircleAvatar(
                        radius: 20.r,
                        backgroundColor: ColorConstants.primaryColor,
                        backgroundImage:
                            user?.avatar != null
                                ? AssetImage(user!.avatar!)
                                : null,
                        child:
                            user?.avatar == null
                                ? Icon(
                                  Icons.person,
                                  size: 20.w,
                                  color: Colors.white,
                                )
                                : null,
                      ),
                    ),
                    SizedBox(width: 10.w),
                    // 用户名和日期
                    Expanded(
                      child: [
                        Text(
                          user?.username ?? 'Unknown',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w700,
                            fontFamily:
                                GoogleFonts.alegreyaSans(
                                  fontWeight: FontWeight.w700,
                                ).fontFamily,
                            color: Colors.black87,
                          ),
                        ),
                        Text(
                          _formatDate(post.timestamp),
                          style: TextStyle(
                            fontSize: 12.sp,
                            fontFamily:
                                GoogleFonts.alegreyaSans(
                                  fontWeight: FontWeight.w400,
                                ).fontFamily,
                            color: Colors.black54,
                          ),
                        ),
                      ].verticalShot(
                        crossAxisAlignment: CrossAxisAlignment.start,
                      ),
                    ),
                    // 导航按钮
                    GestureDetector(
                      onTap: () async {
                        await Navigator.of(context).pushNamed(
                          Routes.momentDetail,
                          arguments: {'postId': post.id},
                        );
                        await model.refresh();
                      },
                      child: Container(
                        width: 32.w,
                        height: 32.w,
                        decoration: BoxDecoration(
                          color: ColorConstants.blueColor,
                          borderRadius: BorderRadius.circular(8.r),
                        ),
                        child: Icon(
                          Icons.arrow_forward,
                          color: Colors.white,
                          size: 16.w,
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 12.h),
                // 内容文字
                Text(
                  post.content,
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontFamily:
                        GoogleFonts.alegreyaSans(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                    color: Colors.black87,
                    height: 1.5,
                  ),
                  maxLines: 4,
                  overflow: TextOverflow.ellipsis,
                ),
                SizedBox(height: 12.h),
                // 图片预览（显示三张图片）
                if (post.images.isNotEmpty)
                  Row(
                    children: [
                      for (int i = 0; i < post.images.length && i < 3; i++) ...[
                        Expanded(
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(6.r),
                            child: Image.asset(
                              post.images[i],
                              width: double.infinity,
                              height: 105.w,
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                        if (i < post.images.length - 1 && i < 2)
                          SizedBox(width: 4.w),
                      ],
                    ],
                  ),
                const Spacer(),
                // 底部操作栏
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 举报图标
                    GestureDetector(
                      onTap: () async {
                        await ComplainHelper.unveil(
                          context,
                          onComplain: (reason) async {
                            await model.deletePost(post.id);
                            if (context.mounted) {
                              FlashNotifier.flashSuccess(
                                'Report submitted successfully',
                              );
                            }
                          },
                        );
                      },
                      child: Image.asset(
                        'assets/images/report.png',
                        width: 20.w,
                        height: 20.w,
                      ),
                    ),
                    // 点赞和评论
                    Row(
                      children: [
                        // 点赞按钮
                        GestureDetector(
                          onTap: () async {
                            if (model.currentUser == null) {
                              final result = await showDialog<bool>(
                                context: context,
                                builder: (context) => const AuthGateModal(),
                              );
                              if (result == true && context.mounted) {
                                await Navigator.of(context).pushNamed('/login');
                                // 返回后刷新登录状态和点赞状态
                                if (context.mounted) {
                                  await model.refresh();
                                }
                              }
                              return;
                            }
                            await model.toggleLike(post.id);
                          },
                          child: Row(
                            children: [
                              Icon(
                                model.isLiked(post.id)
                                    ? Icons.favorite
                                    : Icons.favorite_border,
                                size: 18.w,
                                color:
                                    model.isLiked(post.id)
                                        ? Colors.red
                                        : Colors.black87,
                              ),
                              SizedBox(width: 4.w),
                              Text(
                                '${model.getLikeCount(post.id)}',
                                style: TextStyle(
                                  fontSize: 12.sp,
                                  color: Colors.black87,
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(width: 16.w),
                        // 评论
                        Row(
                          children: [
                            Image.asset(
                              'assets/images/comment.png',
                              width: 18.w,
                              height: 18.w,
                            ),
                            SizedBox(width: 4.w),
                            Text(
                              '12',
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: Colors.black87,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ],
                ),
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建摄影动态页面（瀑布流）
  Widget _buildPhotographyPage(BuildContext context, CommunityViewModel model) {
    if (model.photographyPosts.isEmpty) {
      return Center(
        child: Text(
          'No photography posts yet',
          style: TextStyle(fontSize: 14.sp, color: Colors.grey),
        ),
      );
    }

    // 将每个动态的三张图片展开为独立的项
    // 按照图片索引分组：第一张图片、第二张图片、第三张图片
    final imageItems = <_PhotographyImageItem>[];

    // 先按图片索引分组
    for (int imageIndex = 0; imageIndex < 3; imageIndex++) {
      for (final post in model.photographyPosts) {
        if (imageIndex < post.images.length) {
          imageItems.add(
            _PhotographyImageItem(post: post, imageIndex: imageIndex),
          );
        }
      }
    }

    return SingleChildScrollView(
      padding: EdgeInsets.only(
        left: 14.w,
        right: 14.w,
        bottom: 100.h, // 底部留白，防止被导航栏遮挡
      ),
      child: MasonryGridView.count(
        crossAxisCount: 2,
        mainAxisSpacing: 14.h,
        crossAxisSpacing: 14.w,
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: imageItems.length,
        itemBuilder: (context, index) {
          return _buildPhotographyItem(
            context,
            model,
            imageItems[index].post,
            imageItems[index].imageIndex,
            index,
          );
        },
      ),
    );
  }

  /// 构建单个摄影动态项（瀑布流）
  Widget _buildPhotographyItem(
    BuildContext context,
    CommunityViewModel model,
    MomentShot post,
    int imageIndex,
    int itemIndex,
  ) {
    final user = model.getUserById(post.authorId);
    // 使用默认高度列表，循环使用
    final imageHeight = _waterfallHeights[itemIndex % _waterfallHeights.length];

    return GestureDetector(
      onTap: () async {
        await Navigator.of(
          context,
        ).pushNamed(Routes.photographyDetail, arguments: {'postId': post.id});
        await model.refresh();
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8.r),
        ),
        child: Stack(
          children: [
            // 图片
            ClipRRect(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(8.r),
                topRight: Radius.circular(8.r),
                bottomLeft: Radius.circular(8.r),
                bottomRight: Radius.circular(8.r),
              ),
              child:
                  post.images.isNotEmpty && imageIndex < post.images.length
                      ? Image.asset(
                        post.images[imageIndex],
                        width: double.infinity,
                        height: imageHeight.h,
                        fit: BoxFit.cover,
                      )
                      : Container(
                        width: double.infinity,
                        height: imageHeight.h,
                        color: Colors.grey[300],
                      ),
            ),
            // 用户头像（放在图片左上角，带毛玻璃效果装饰）
            Positioned(
              top: 8.h,
              left: 8.w,
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8.r),
                child: BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                  child: Container(
                    padding: EdgeInsets.all(3.w),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(8.r),
                      border: Border.all(
                        color: Colors.white.withOpacity(0.5),
                        width: 1.5.w,
                      ),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.15),
                          blurRadius: 6,
                          spreadRadius: 1,
                        ),
                      ],
                    ),
                    child: Container(
                      width: 28.w,
                      height: 28.w,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6.r),
                        image:
                            user?.avatar != null
                                ? DecorationImage(
                                  image: AssetImage(user!.avatar!),
                                  fit: BoxFit.cover,
                                )
                                : null,
                        color:
                            user?.avatar == null
                                ? ColorConstants.primaryColor
                                : null,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.1),
                            blurRadius: 4,
                            offset: Offset(2, 2),
                            spreadRadius: 0,
                          ),
                        ],
                      ),
                      child:
                          user?.avatar == null
                              ? Icon(
                                Icons.person,
                                size: 16.w,
                                color: Colors.white,
                              )
                              : null,
                    ),
                  ),
                ),
              ),
            ),
            // 底部信息（放在图片底部）
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 8.h),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [Colors.transparent, Colors.black.withOpacity(0.6)],
                  ),
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(8.r),
                    bottomRight: Radius.circular(8.r),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    // 点赞按钮
                    GestureDetector(
                      onTap: () async {
                        if (model.currentUser == null) {
                          final result = await showDialog<bool>(
                            context: context,
                            builder: (context) => const AuthGateModal(),
                          );
                          if (result == true && context.mounted) {
                            await Navigator.of(context).pushNamed('/login');
                            // 返回后刷新登录状态和点赞状态
                            if (context.mounted) {
                              await model.refresh();
                            }
                          }
                          return;
                        }
                        await model.toggleLike(post.id);
                      },
                      child: Row(
                        children: [
                          Icon(
                            model.isLiked(post.id)
                                ? Icons.favorite
                                : Icons.favorite_border,
                            size: 14.w,
                            color: Colors.white,
                          ),
                          SizedBox(width: 4.w),
                          Text(
                            '${model.getLikeCount(post.id)}',
                            style: TextStyle(
                              fontSize: 10.sp,
                              color: Colors.white,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Row(
                      children: [
                        Image.asset(
                          'assets/images/eye.png',
                          width: 14.w,
                          height: 14.w,
                          color: Colors.white,
                        ),
                        SizedBox(width: 4.w),
                        Text(
                          '${post.viewCount}',
                          style: TextStyle(
                            fontSize: 10.sp,
                            color: Colors.white,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 格式化日期
  String _formatDate(DateTime date) {
    return '${date.year}.${date.month.toString().padLeft(2, '0')}.${date.day.toString().padLeft(2, '0')}';
  }
}

/// 摄影动态图片项
/// 用于将动态的三张图片展开为独立的瀑布流项
class _PhotographyImageItem {
  final MomentShot post;
  final int imageIndex;

  _PhotographyImageItem({required this.post, required this.imageIndex});
}
